<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="data.queryInfo.query"
            @clear="getUserList"
            clearable
          >
            <template #append>
              <el-button :icon="Search" @click="getUserList" />
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="data.addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 列表区域 -->
      <el-table :data="data.userlist" border stripe style="width: 100%">
        <el-table-column type="index" :index="1" width="50" />
        <el-table-column prop="username" label="用户名" width="180" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="role" label="角色" width="180" />
        <el-table-column prop="state" label="状态" width="180">
          <template #default="scope">
            <el-switch
              v-model="scope.row.state"
              @change="userStateChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <!-- 修改按钮 -->
            <el-button size="small" @click="showEditDialog(scope.row.id)"
              >修改</el-button
            >
            <!-- 删除按钮 -->
            <el-button
              size="small"
              type="danger"
              @click="removeUserByID(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        background
        layout="total, prev, pager, next"
        :total="data.total"
        :page-sizes="[1, 2, 5, 10]"
        v-model:page-size="data.queryInfo.pagesize"
        v-model:current-page="data.queryInfo.pagenum"
        @current-change="handleChangepage"
      ></el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      width="50%"
      v-model="data.addDialogVisible"
      @close="addDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        ref="addFormRef"
        :model="data.addForm"
        :rules="data.addFormRules"
        label-width="70px"
        status-icon
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="data.addForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="data.addForm.password" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="data.addForm.email" />
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addUser"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog
      title="修改用户信息"
      width="50%"
      v-model="data.editDialogVisible"
      @close="editDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        ref="editFormRef"
        :model="data.editForm"
        :rules="data.editFormRules"
        label-width="70px"
        status-icon
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="data.editForm.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="data.editForm.email" />
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editUser"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import { ArrowRight, Search } from "@element-plus/icons-vue";
import API from "../../plugins/axiosInstance";

const checkEmail = (rule, value, cb) => {
  // 验证邮箱的正则表达式
  const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;

  if (regEmail.test(value)) {
    // 合法的邮箱
    return cb();
  }

  cb(new Error("请输入合法的邮箱"));
};
const addFormRef = ref(null);
const editFormRef = ref(null);
const data = reactive({
  userlist: [],
  total: 0,
  queryInfo: {
    query: "",
    // 当前的页数
    pagenum: 1,
    // 当前每页显示多少条数据
    pagesize: 5,
  },
  addDialogVisible: false,
  // 添加用户的表单数据
  addForm: {
    username: "",
    password: "",
    email: "",
  },
  addFormRules: {
    username: [
      { required: true, message: "请输入内容", trigger: "blur" },
      { min: 3, max: 10, message: "长度在3~10个字符之间", trigger: "blur" },
    ],
    password: [
      { required: true, message: "请输入内容", trigger: "blur" },
      { min: 6, max: 15, message: "长度在6~15个字符之间", trigger: "blur" },
    ],
    email: [
      { required: true, message: "请输入内容", trigger: "blur" },
      { validator: checkEmail, trigger: "blur" },
    ],
  },
  // 控制修改用户对话框的显示和隐藏
  editDialogVisible: false,
  // 查询到的用户信息
  editForm: {
    id: "",
    username: "",
    email: "",
  },
  editFormRules: {
    username: [
      { required: true, message: "请输入内容", trigger: "blur" },
      { min: 3, max: 10, message: "长度在3~10个字符之间", trigger: "blur" },
    ],
    email: [
      { required: true, message: "请输入内容", trigger: "blur" },
      { validator: checkEmail, trigger: "blur" },
    ],
  },
});

onMounted(() => {
  getUserList();
});

const getUserList = () => {
  API.get("users", {
    params: data.queryInfo,
  }).then((res) => {
    let { data: result } = res;
    // state由 number 转化为 boolean
    data.userlist = result.data.users.map((item, index, array) => {
      item.state = item.state == 1 ? true : false;
      return item;
    });
    data.userlist = result.data.users;
    data.total = result.data.total;
  });
};
const handleChangepage = (newValue) => {
  data.queryInfo.pagenum = newValue;
  getUserList();
};
// 监听 Switch 开关状态的转变
const userStateChange = (userInfo) => {
  console.log(`/users/${userInfo.id}/state/${Number(userInfo.state)}`);
  API.get(`/users/${userInfo.id}/state/${Number(userInfo.state)}`).then(
    (response) => {
      let { data: res } = response;
      if (res.meta.status !== 200) {
        userInfo.state = !userInfo.state;
        return ElMessage.error("更新用户状态失败!");
      }
      ElMessage.success("更新用户状态成功!");
    }
  );
};
// 监听添加用户对话框的关闭
const addDialogClosed = () => {
  addFormRef.value.resetFields();
};
// 点击按钮，添加用户
const addUser = () => {
  addFormRef.value.validate((valid) => {
    if (!valid) return;
    // 可以发起添加用户的网络请求
    API.post("users", data.addForm).then(({ data: res }) => {
      if (res.meta.status !== 201) {
        ElMessage.error("添加用户失败！");
      }
      ElMessage.success("添加用户成功！");
      data.addDialogVisible = false;
      // 重新获取用户列表
      getUserList();
    });
  });
};
// 展示修改用户的对话框
const showEditDialog = (id) => {
  API.get("users/" + id).then(({ data: res }) => {
    if (res.meta.status !== 200) {
      return ElMessage.error("查询用户失败！");
    }
    data.editForm = res.data;
    data.editDialogVisible = true;
  });
};
// 监听修改用户对话框的关闭
const editDialogClosed = () => {
  editFormRef.value.resetFields();
};
// 修改用户信息并提交
const editUser = () => {
  editFormRef.value.validate((value) => {
    if (!value) return;
    // 发起修改用户信息的请求
    API.put("users/" + data.editForm.id, {
      username: data.editForm.username,
      email: data.editForm.email,
    }).then(({ data: res }) => {
      if (res.meta.status !== 200) {
        return ElMessage.error("更新用户失败！");
      }
      // 关闭对话框
      data.editDialogVisible = false;
      // 刷新数据列表
      getUserList();
      // 提示修改成功
      ElMessage.success("更新用户成功！");
    });
  });
};
// 通过 id 删除用户
const removeUserByID = (id) => {
  ElMessageBox.confirm("此操作会永久删除该用户，是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then((res) => {
      console.log("确认删除");
      API.delete("users/" + id).then(({ data: res }) => {
        if (res.meta.status !== 200) {
          return ElMessage.error("删除失败！");
        }
        getUserList();
        ElMessage.success("删除成功");
      });
    })
    .catch((err) => {
      ElMessage.info("已取消删除");
    });
};
</script>

<style scoped></style>
